<template>
  <div class="app-container">
    <!-- 页面标题和统计信息 -->
    <div class="page-header" data-aos="fade-down">
      <div class="page-title">
        <i class="el-icon-s-opportunity"></i>
        <span>心率传感器数据管理</span>
      </div>
      <div class="page-description">
        实时监控和管理所有心率传感器数据，确保用户健康状态正常
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards" data-aos="fade-up" data-aos-delay="100">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card heart-card">
          <div class="stats-icon pulse-animation">
            <i class="el-icon-first-aid-kit"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">平均心率</div>
            <div class="stats-value">{{ averageHeartRate }} <span class="unit">bpm</span></div>
            <div class="stats-trend">
              <i class="el-icon-top" v-if="heartRateTrend > 0"></i>
              <i class="el-icon-bottom" v-if="heartRateTrend < 0"></i>
              <i class="el-icon-minus" v-if="heartRateTrend === 0"></i>
              <span>{{ Math.abs(heartRateTrend) }}%</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card normal-card">
          <div class="stats-icon">
            <i class="el-icon-success"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">正常范围</div>
            <div class="stats-value">{{ normalCount }}</div>
            <div class="stats-percentage">{{ normalPercentage }}%</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card warning-card">
          <div class="stats-icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">异常数据</div>
            <div class="stats-value">{{ abnormalCount }}</div>
            <div class="stats-percentage">{{ abnormalPercentage }}%</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card user-card">
          <div class="stats-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="stats-content">
            <div class="stats-title">监测用户</div>
            <div class="stats-value">{{ userCount }}</div>
            <div class="stats-detail">活跃用户</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 心率趋势图表 -->
    <el-card class="chart-card" shadow="hover" data-aos="fade-up" data-aos-delay="150">
      <div slot="header" class="card-header">
        <span><i class="el-icon-data-line"></i> 心率趋势图</span>
        <div class="chart-controls">
          <el-switch
            v-model="realTimeUpdate"
            active-text="实时更新"
            inactive-text="手动刷新"
            @change="handleRealTimeToggle"
          ></el-switch>
          <el-radio-group v-model="chartTimeRange" size="small" @change="updateChartData">
            <el-radio-button label="1h">1小时</el-radio-button>
            <el-radio-button label="6h">6小时</el-radio-button>
            <el-radio-button label="1d">1天</el-radio-button>
            <el-radio-button label="7d">7天</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="chart-container" ref="heartRateChart" style="height: 300px;"></div>
    </el-card>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover" data-aos="fade-up" data-aos-delay="200">
      <div slot="header" class="card-header">
        <span><i class="el-icon-search"></i> 数据筛选</span>
        <el-button type="text" @click="showSearch = !showSearch">
          {{ showSearch ? '收起' : '展开' }}
          <i :class="showSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        </el-button>
      </div>
      <el-collapse-transition>
        <div v-show="showSearch">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
            <el-form-item label="关联设备ID" prop="deviceId">
              <el-input
                v-model="queryParams.deviceId"
                placeholder="请输入关联设备ID"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="心率值(BPM)" prop="heartRate">
              <el-input
                v-model="queryParams.heartRate"
                placeholder="请输入心率值(BPM)"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="心率状态" prop="heartRateStatus">
              <el-select v-model="queryParams.heartRateStatus" placeholder="请选择心率状态" clearable>
                <el-option label="正常" value="normal"></el-option>
                <el-option label="偏高" value="high"></el-option>
                <el-option label="偏低" value="low"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据采集时间">
              <el-date-picker
                v-model="daterangeRecordTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="入库时间">
              <el-date-picker
                v-model="daterangeCreateTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card" shadow="hover" data-aos="fade-up" data-aos-delay="300">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-opportunity"></i> 心率传感器数据</span>
        <div class="card-operations">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
            v-hasPermi="['system:heartRateSensor:add']"
          >新增数据</el-button>
          <el-button
            type="success"
            icon="el-icon-edit"
            size="small"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:heartRateSensor:edit']"
          >批量修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:heartRateSensor:remove']"
          >批量删除</el-button>
          <el-button
            type="warning"
            icon="el-icon-download"
            size="small"
            @click="handleExport"
            v-hasPermi="['system:heartRateSensor:export']"
          >导出数据</el-button>
          <el-button
            type="info"
            icon="el-icon-data-analysis"
            size="small"
            @click="handleDataAnalysis"
            v-hasPermi="['system:heartRateSensor:analysis']"
          >数据分析</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="heartRateSensorList" 
        @selection-change="handleSelectionChange"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        :cell-style="{padding: '8px 0'}"
        border
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="记录ID" align="center" prop="id" width="80" sortable="custom" />
        <el-table-column label="设备ID" align="center" prop="deviceId" width="120">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewDeviceDetails(scope.row.deviceId)">
              <i class="el-icon-monitor"></i> {{ scope.row.deviceId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="心率值" align="center" prop="heartRate" width="120" sortable="custom">
          <template slot-scope="scope">
            <div class="heart-rate-display">
              <div class="heart-value" :class="getHeartRateClass(scope.row.heartRate)">
                {{ scope.row.heartRate }}
                <span class="unit">bpm</span>
              </div>
              <div class="heart-icon">
                <i class="el-icon-first-aid-kit" :class="getHeartRateIconClass(scope.row.heartRate)"></i>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.heartRate)" effect="dark">
              <i class="el-icon-warning-outline" v-if="getStatusType(scope.row.heartRate) === 'danger'"></i>
              <i class="el-icon-warning" v-if="getStatusType(scope.row.heartRate) === 'warning'"></i>
              <i class="el-icon-success" v-if="getStatusType(scope.row.heartRate) === 'success'"></i>
              {{ getStatusText(scope.row.heartRate) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="采集时间" align="center" prop="recordTime" width="180" sortable="custom">
          <template slot-scope="scope">
            <div class="time-display">
              <div class="time-value">{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</div>
              <div class="time-detail">{{ parseTime(scope.row.recordTime, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center" prop="createTime" width="180" sortable="custom">
          <template slot-scope="scope">
            <div class="time-display">
              <div class="time-value">{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</div>
              <div class="time-detail">{{ parseTime(scope.row.createTime, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              class="action-btn view-btn"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:heartRateSensor:edit']"
              class="action-btn edit-btn"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:heartRateSensor:remove']"
              class="action-btn delete-btn"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改心率传感器数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="关联设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入关联设备ID" />
        </el-form-item>
        <el-form-item label="心率值(BPM)" prop="heartRate">
          <el-input-number v-model="form.heartRate" :min="30" :max="200" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="数据采集时间" prop="recordTime">
          <el-date-picker
            v-model="form.recordTime"
            type="datetime"
            placeholder="选择数据采集时间"
            style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 数据详情对话框 -->
    <el-dialog title="心率传感器数据详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ currentRow.id }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ currentRow.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="心率值">{{ currentRow.heartRate }} BPM</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentRow.heartRate)">{{ getStatusText(currentRow.heartRate) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="数据采集时间">{{ parseTime(currentRow.recordTime) }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ parseTime(currentRow.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHeartRateSensor, getHeartRateSensor, delHeartRateSensor, addHeartRateSensor, updateHeartRateSensor } from "@/api/system/heartRateSensor"
import * as echarts from 'echarts'

export default {
  name: "HeartRateSensor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 心率传感器数据表格数据
      heartRateSensorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 当前查看的行数据
      currentRow: {},
      // 心率值(BPM)时间范围
      daterangeRecordTime: [],
      // 心率值(BPM)时间范围
      daterangeCreateTime: [],
      // 图表时间范围
      chartTimeRange: '1d',
      // 图表实例
      chart: null,
      // 实时更新开关
      realTimeUpdate: false,
      // 实时更新定时器
      realTimeTimer: null,
      // 实时更新间隔（毫秒）
      realTimeInterval: 30000,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        heartRate: null,
        recordTime: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "关联设备ID不能为空", trigger: "blur" }
        ],
        heartRate: [
          { required: true, message: "心率值(BPM)不能为空", trigger: "blur" }
        ],
        recordTime: [
          { required: true, message: "数据采集时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    // 计算平均心率
    averageHeartRate() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length === 0) return '0';
      const sum = this.heartRateSensorList.reduce((acc, item) => acc + parseInt(item.heartRate || 0), 0);
      return Math.round(sum / this.heartRateSensorList.length);
    },
    // 计算正常范围数据数量
    normalCount() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length === 0) return 0;
      return this.heartRateSensorList.filter(item => {
        const heartRate = parseInt(item.heartRate);
        return heartRate >= 60 && heartRate <= 100;
      }).length;
    },
    // 计算异常数据数量
    abnormalCount() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length === 0) return 0;
      return this.heartRateSensorList.filter(item => {
        const heartRate = parseInt(item.heartRate);
        return heartRate < 60 || heartRate > 100;
      }).length;
    },
    // 计算监测用户数
    userCount() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length === 0) return 0;
      const uniqueDevices = new Set(this.heartRateSensorList.map(item => item.deviceId));
      return uniqueDevices.size;
    },
    // 计算正常数据百分比
    normalPercentage() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length === 0) return '0';
      return Math.round((this.normalCount / this.heartRateSensorList.length) * 100);
    },
    // 计算异常数据百分比
    abnormalPercentage() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length === 0) return '0';
      return Math.round((this.abnormalCount / this.heartRateSensorList.length) * 100);
    },
    // 计算心率趋势
    heartRateTrend() {
      if (!this.heartRateSensorList || this.heartRateSensorList.length < 2) return 0;
      // 简单计算最近数据与之前数据的平均值比较
      const recentData = this.heartRateSensorList.slice(0, Math.ceil(this.heartRateSensorList.length / 2));
      const previousData = this.heartRateSensorList.slice(Math.ceil(this.heartRateSensorList.length / 2));
      
      const recentAvg = recentData.reduce((acc, item) => acc + parseInt(item.heartRate || 0), 0) / recentData.length;
      const previousAvg = previousData.reduce((acc, item) => acc + parseInt(item.heartRate || 0), 0) / previousData.length;
      
      return Math.round(((recentAvg - previousAvg) / previousAvg) * 100);
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    window.removeEventListener('resize', this.handleResize)
    // 清理实时更新定时器
    this.stopRealTimeUpdate()
  },
  methods: {
    /** 查询心率传感器数据列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeRecordTime && '' != this.daterangeRecordTime) {
        this.queryParams.params["beginRecordTime"] = this.daterangeRecordTime[0]
        this.queryParams.params["endRecordTime"] = this.daterangeRecordTime[1]
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listHeartRateSensor(this.queryParams).then(response => {
        this.heartRateSensorList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        heartRate: null,
        recordTime: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRecordTime = []
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加心率传感器数据"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getHeartRateSensor(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改心率传感器数据"
      })
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.currentRow = row
      this.detailOpen = true
    },
    /** 查看设备详情 */
    viewDeviceDetails(deviceId) {
      this.$router.push({
        path: '/system/device',
        query: { deviceId: deviceId }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHeartRateSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addHeartRateSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除心率传感器数据编号为"' + ids + '"的数据项？').then(function() {
        return delHeartRateSensor(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/heartRateSensor/export', {
        ...this.queryParams
      }, `heartRateSensor_${new Date().getTime()}.xlsx`)
    },
    /** 数据分析按钮操作 */
    handleDataAnalysis() {
      this.$modal.msgLoading('正在分析数据，请稍候...');
      
      // 模拟数据分析API调用
      setTimeout(() => {
        this.$modal.closeLoading();
        
        // 显示分析结果对话框
        this.$alert(`
          <div style="text-align: left;">
            <h3>心率传感器数据分析报告</h3>
            <p><strong>分析时间：</strong>${this.parseTime(new Date())}</p>
            <p><strong>数据范围：</strong>${this.getDateRangeText()}</p>
            <hr>
            <h4>心率数据统计</h4>
            <ul>
              <li>平均心率：${this.averageHeartRate} bpm</li>
              <li>正常心率数据：${this.normalCount} 条 (${this.normalPercentage}%)</li>
              <li>异常心率数据：${this.abnormalCount} 条 (${this.abnormalPercentage}%)</li>
              <li>监测用户数量：${this.userCount} 人</li>
            </ul>
            <h4>趋势分析</h4>
            <p>• 异常心率占比${this.abnormalPercentage > 15 ? '偏高' : '正常'}，建议${this.abnormalPercentage > 15 ? '关注用户健康状况' : '继续保持'}</p>
            <p>• 平均心率${this.averageHeartRate < 60 ? '偏低' : this.averageHeartRate > 100 ? '偏高' : '正常'}，${this.averageHeartRate < 60 ? '可能存在健康风险' : this.averageHeartRate > 100 ? '建议进行健康检查' : '心率状态良好'}</p>
            <h4>建议</h4>
            <p>• ${this.abnormalPercentage > 15 ? '建议关注异常心率用户，提供健康建议' : '用户心率状态良好，继续保持'}</p>
            <p>• ${this.userCount < 10 ? '监测用户数量较少，建议增加用户覆盖' : '监测用户数量充足，数据具有代表性'}</p>
            <p>• ${this.heartRateTrend > 5 ? '心率呈上升趋势，建议关注用户活动状态' : this.heartRateTrend < -5 ? '心率呈下降趋势，建议检查设备状态' : '心率趋势稳定，无需特别关注'}</p>
          </div>
        `, '数据分析结果', {
          dangerouslyUseHTMLString: true,
          customClass: 'analysis-dialog'
        });
      }, 1500);
    },
    /** 获取日期范围文本 */
    getDateRangeText() {
      if (this.daterangeRecordTime && this.daterangeRecordTime.length === 2) {
        return `${this.daterangeRecordTime[0]} 至 ${this.daterangeRecordTime[1]}`;
      }
      return '全部数据';
    },
    /** 获取心率状态类型 */
    getHeartRateType(heartRate) {
      const value = parseInt(heartRate);
      if (value < 60 || value > 100) return 'danger';
      if (value < 70 || value > 90) return 'warning';
      return 'success';
    },
    /** 获取状态类型 */
    getStatusType(heartRate) {
      return this.getHeartRateType(heartRate);
    },
    /** 获取状态文本 */
    getStatusText(heartRate) {
      const rate = parseInt(heartRate);
      if (rate < 60 || rate > 100) return '异常';
      if (rate < 65 || rate > 95) return '警告';
      return '正常';
    },
    /** 获取心率值样式类 */
    getHeartRateClass(heartRate) {
      const rate = parseInt(heartRate);
      if (rate < 60 || rate > 100) return 'heart-rate-danger';
      if (rate < 65 || rate > 95) return 'heart-rate-warning';
      return 'heart-rate-normal';
    },
    /** 获取心率图标样式类 */
    getHeartRateIconClass(heartRate) {
      const rate = parseInt(heartRate);
      if (rate < 60 || rate > 100) return 'pulse-danger';
      if (rate < 65 || rate > 95) return 'pulse-warning';
      return 'pulse-normal';
    },
    /** 初始化图表 */
    initChart() {
      if (!this.$refs.heartRateChart) return;
      
      this.chart = echarts.init(this.$refs.heartRateChart);
      this.updateChartData();
    },
    /** 实时更新开关处理 */
    handleRealTimeToggle(value) {
      if (value) {
        this.startRealTimeUpdate();
      } else {
        this.stopRealTimeUpdate();
      }
    },
    /** 开始实时更新 */
    startRealTimeUpdate() {
      this.stopRealTimeUpdate(); // 先停止现有的定时器
      
      this.realTimeTimer = setInterval(() => {
        this.getList(); // 获取最新数据
        this.updateChartData(); // 更新图表
        this.$notify({
          title: '数据更新',
          message: '心率传感器数据已自动更新',
          type: 'success',
          duration: 2000
        });
      }, this.realTimeInterval);
    },
    /** 停止实时更新 */
    stopRealTimeUpdate() {
      if (this.realTimeTimer) {
        clearInterval(this.realTimeTimer);
        this.realTimeTimer = null;
      }
    },
    /** 更新图表数据 */
    updateChartData() {
      if (!this.chart) return;
      
      // 模拟数据，实际应用中应该从API获取
      const now = new Date();
      const data = [];
      const times = [];
      
      // 根据时间范围生成数据点
      let dataPoints = 24; // 默认1天24个点
      let timeFormat = '{h}:{i}';
      
      switch (this.chartTimeRange) {
        case '1h':
          dataPoints = 12;
          timeFormat = '{h}:{i}';
          break;
        case '6h':
          dataPoints = 18;
          timeFormat = '{h}:{i}';
          break;
        case '1d':
          dataPoints = 24;
          timeFormat = '{h}:{i}';
          break;
        case '7d':
          dataPoints = 7;
          timeFormat = '{m}-{d}';
          break;
      }
      
      // 生成模拟数据
      for (let i = dataPoints - 1; i >= 0; i--) {
        const time = new Date(now);
        
        if (this.chartTimeRange === '1h') {
          time.setMinutes(now.getMinutes() - i * 5);
        } else if (this.chartTimeRange === '6h') {
          time.setMinutes(now.getMinutes() - i * 20);
        } else if (this.chartTimeRange === '1d') {
          time.setHours(now.getHours() - i);
        } else if (this.chartTimeRange === '7d') {
          time.setDate(now.getDate() - i);
        }
        
        times.push(this.parseTime(time, timeFormat));
        
        // 生成随机心率数据，范围在60-100之间
        const baseHeartRate = 75;
        const variation = Math.random() * 20 - 10;
        data.push(Math.round(baseHeartRate + variation));
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>心率: ${params[0].value} bpm`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times
        },
        yAxis: {
          type: 'value',
          min: 50,
          max: 110,
          axisLabel: {
            formatter: '{value} bpm'
          }
        },
        series: [
          {
            name: '心率',
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#F56C6C'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(245, 108, 108, 0.5)' },
                { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
              ])
            },
            data: data,
            markLine: {
              data: [
                { yAxis: 60, name: '最低正常值' },
                { yAxis: 100, name: '最高正常值' }
              ],
              label: {
                formatter: '{b}'
              }
            }
          }
        ]
      };
      
      this.chart.setOption(option);
    },
    /** 处理表格排序 */
    handleSortChange({ column, prop, order }) {
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = order === 'ascending';
      this.getList();
    },
    /** 处理窗口大小变化 */
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  watch: {
    chartTimeRange() {
      this.updateChartData();
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.page-header {
  margin-bottom: 20px;
  
  .page-title {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 10px;
    
    i {
      margin-right: 10px;
      color: #F56C6C;
    }
  }
  
  .page-description {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;
  }
}

.stats-cards {
  margin-bottom: 20px;
  
  .stats-card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }
    
    .stats-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      
      i {
        font-size: 24px;
      }
    }
    
    .stats-content {
      flex: 1;
      
      .stats-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .stats-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
}

.search-card, .table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    span {
      font-weight: 600;
      color: #303133;
      
      i {
        margin-right: 8px;
        color: #F56C6C;
      }
    }
  }
  
  .card-operations {
    display: flex;
    gap: 10px;
  }
}

.el-table {
  margin-top: 0;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  ::v-deep .el-table__cell {
    padding: 8px 0;
  }
  
  ::v-deep .el-table th.el-table__cell {
    padding: 12px 0;
  }
  
  ::v-deep .el-table td.el-table__cell {
    border-right: none;
  }
  
  ::v-deep .el-table--border .el-table__cell {
    border-right: none;
  }
  
  ::v-deep .el-table--group::after, 
  ::v-deep .el-table--border::after, 
  ::v-deep .el-table::before {
    background-color: transparent;
  }
  
  .device-id {
    font-family: 'Courier New', monospace;
    background: #f5f7fa;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .time-display {
    display: flex;
    flex-direction: column;
    
    .date {
      font-size: 12px;
      color: #909399;
    }
    
    .time {
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }
  }
  
  .action-buttons {
    .el-button {
      margin-left: 5px;
      padding: 5px 8px;
      transition: all 0.2s ease;
      
      &.el-button--text {
        &:hover {
          background-color: rgba(64, 158, 255, 0.1);
          transform: scale(1.1);
        }
      }
    }
  }
}

.el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: none;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  }
}

.heart-card {
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #F56C6C, #E6A23C);
  }
  
  .card-icon {
    font-size: 24px;
    color: #F56C6C;
    margin-right: 12px;
  }
  
  .card-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }
  
  .card-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }
  
  .card-desc {
    font-size: 12px;
    color: #C0C4CC;
  }
}

.normal-card {
  &::before {
    background: linear-gradient(to bottom, #67C23A, #409EFF);
  }
  
  .card-icon {
    color: #67C23A;
  }
}

.warning-card {
  &::before {
    background: linear-gradient(to bottom, #E6A23C, #F56C6C);
  }
  
  .card-icon {
    color: #E6A23C;
  }
}

.danger-card {
  &::before {
    background: linear-gradient(to bottom, #F56C6C, #E6A23C);
  }
  
  .card-icon {
    color: #F56C6C;
  }
}

.pulse-animation {
  display: inline-block;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.chart-container {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .chart-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
    
    .time-range-selector {
      .el-radio-group {
        .el-radio-button__inner {
          padding: 8px 16px;
          font-size: 12px;
        }
      }
    }
  }
  
  .chart {
    height: 300px;
    width: 100%;
  }
}

.el-switch {
  margin-right: 10px;
  
  .el-switch__label {
    color: #606266;
    font-size: 13px;
  }
}

.heart-rate-normal {
  color: #67C23A;
  font-weight: bold;
}

.heart-rate-warning {
  color: #E6A23C;
  font-weight: bold;
}

.heart-rate-danger {
  color: #F56C6C;
  font-weight: bold;
}

.pulse-normal {
  color: #67C23A;
  animation: pulse 2s infinite;
}

.pulse-warning {
  color: #E6A23C;
  animation: pulse 1.5s infinite;
}

.pulse-danger {
  color: #F56C6C;
  animation: pulse 1s infinite;
}

.device-id {
  font-family: 'Courier New', monospace;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.time-display {
  display: flex;
  flex-direction: column;
  
  .date {
    font-size: 12px;
    color: #909399;
  }
  
  .time {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
  }
}

.action-buttons {
  .el-button {
    margin-left: 5px;
    padding: 5px 8px;
    
    &.el-button--text {
      &:hover {
        background-color: rgba(64, 158, 255, 0.1);
      }
    }
  }
}

// 数据分析对话框样式
.analysis-dialog {
  .el-message-box {
    max-width: 600px;
    
    .el-message-box__content {
      max-height: 500px;
      overflow-y: auto;
    }
    
    h3 {
      color: #409EFF;
      margin-bottom: 15px;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 8px;
    }
    
    h4 {
      color: #303133;
      margin-top: 15px;
      margin-bottom: 10px;
    }
    
    ul {
      padding-left: 20px;
      
      li {
        margin-bottom: 5px;
        line-height: 1.5;
      }
    }
    
    hr {
      border: none;
      border-top: 1px solid #EBEEF5;
      margin: 15px 0;
    }
    
    p {
      line-height: 1.6;
      margin-bottom: 8px;
    }
  }
}

// 响应式布局
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .stats-cards {
    .el-col {
      margin-bottom: 15px;
    }
  }
  
  .card-operations {
    flex-direction: column;
    gap: 5px;
  }
}
</style>